﻿/* Directory 扩展类
 */

/* 未完事项
 * 1、单元测试。
 */
namespace LSLib.IO
{
    using System;
    using System.IO;

    public static class DirectoryEx
    {
        /// <summary>文件夹重命名
        /// </summary>
        /// <param name="sourceDirectory">需要重命名的原文件夹(带路径)</param>
        /// <param name="newDirName">新的文件夹名(不带路径)</param>
        public static bool Rename(string sourceDirectory, string newDirName)
        {
            if (Directory.Exists(sourceDirectory) == false) throw new DirectoryNotFoundException(string.Format("待重命名的文件夹不存在!/r/n{0}", sourceDirectory));
            if (string.IsNullOrEmpty(newDirName)) throw new ArgumentNullException("newDirName");

            string destDirName = Path.Combine(Path.GetDirectoryName(sourceDirectory), newDirName);
            Directory.Move(sourceDirectory, destDirName);
            return Directory.Exists(destDirName);
        }

        /// <summary>文件夹的整体复制操作
        /// </summary>
        /// <param name="sourcePath">原路径</param>
        /// <param name="destPath">目的路径</param>
        public static void CopyAll(string sourcePath, string destPath)
        {
            if (Directory.Exists(sourcePath) == false) throw new DirectoryNotFoundException(string.Format("文件夹不存在!/r/n{0}", sourcePath));
            if (string.IsNullOrEmpty(destPath)) throw new ArgumentNullException("destPath");

            if (Directory.Exists(destPath) == false) Directory.CreateDirectory(destPath);

            string[] files = Directory.GetFiles(sourcePath);
            foreach (string file in files)
            {
                string destFile = Path.Combine(destPath, Path.GetFileName(file));
                File.Copy(file, destFile);
            }

            string[] dirs = Directory.GetDirectories(sourcePath);
            foreach (string dir in dirs)
            {
                DirectoryInfo dirInfo = new DirectoryInfo(dir);
                string sDir = Path.Combine(sourcePath, dirInfo.Name);
                string dDir = Path.Combine(destPath, dirInfo.Name);
                CopyAll(sDir, dDir);
            }
        }

        /// <summary>判断目标是否为【目录】
        /// </summary>
        /// <param name="path">待检查的路径</param>
        /// <returns>true=目录；false=非目录。</returns>
        public static bool IsDirectory(string path)
        {
            return (File.GetAttributes(path).CompareTo(FileAttributes.Directory) == 0);
        }
    }
}